import { findHeadCategory } from '@/api/home.js'
// 提供默认的分类数据，防止出现空白的分类效果
import { category } from '@/utils/constant.js'
export default {
  namespaced: true,
  state: () => {
    return {
      list: category.map((item, i) => ({ id: i, name: item }))// 分类列表
    }
  },
  // 加载数据成功后需要修改list所以需要mutations函数
  mutations: {
    setList (state, value) {
      state.list = value
    },
    updateCatestatu (state, value) {
      const cate = state.list.find(item => item.id === value.id)
      if (cate) {
        cate.open = value.open
      }
    }
  },
  // 需要向后台加载数据，所以需要actions函数获取数据
  actions: {
    async setList (state) {
      const res = await findHeadCategory()
      res.result.forEach((item) => {
        item.open = false
      })
      state.commit('setList', res.result)
    }
  },
  getters: {
    cateList (state) {
      return state.list.map((item) => {
        return {
          ...item,
          children: item.children && item.children.filter((item, i) => {
            return i < 2
          })
        }
      })
    }
  }
}
